<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Yipin
  Date: 2016/11/15
  Time: 10:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="../../include/head.jsp">
    <jsp:param name="title" value="机床IDLE原因处置"/>
</jsp:include>

<jsp:include page="../../include/tenant_header.jsp"/>

<jsp:include page="../../include/tenant_sidebar.jsp"/>

<div class="content-wrapper content-wrapper-bg">
    <section class="content-header">
        <h4 class="page-title" style="display: inline-block"><spring:message
                code="label.tenant.idleReason.deal"></spring:message></h4>

        <div style="float: right;margin-right: 40px;">
            <div class="sie-calendar-parent">
                <input type="text" readonly="readonly" class="form-control sie-calendar-input" id="hoursTimeLine">
                <img src="/images/calendar.png" class="sie-calendar-img">
            </div>
        </div>
    </section>
    <section class="content">
        <div class="box box-primary table-header-line">
            <div class="box-body" style="padding: 0">
                <div class="row" style="padding: 10px 0 35px 0;">
                    <div class="col-md-4" style="padding-left:5%">
                        <span><spring:message code="label.device.type"/> ：</span>
                        <select id="deviceType" class="form-control sie-input-border sie-input-uwh"
                                style="padding: 2px 12px;margin-right: 0" onchange="changeType()">
                            <option value="-1"><spring:message code="label.select"/></option>
                        </select>
                    </div>
                    <div class="col-md-4" style="padding-left:5%">
                        <span><spring:message code="label.device.model"/> ：</span>
                        <select id="deviceModel" class="form-control sie-input-border sie-input-uwh"
                                style="padding: 2px 12px;margin-right: 0" onchange="changeModel()">
                            <option value="-1"><spring:message code="label.select"/></option>
                        </select>
                    </div>
                    <div class="col-md-4" style="padding-left:5%">
                        <span><spring:message code="label.device.name"/>：</span>
                        <select id="deviceUniqueId" class="form-control sie-input-border sie-input-uwh"
                                style="padding: 2px 12px;margin-right: 0" onchange="changeUniqueId()">
                            <option value="-1"><spring:message code="label.select"/></option>
                        </select>
                    </div>
                </div>
                <div id="line" class="hidden" style="padding:20px 20px 50px 20px;">
                    <div style="width: 100%;border:1px solid #cdd9e1;background-color: #fff;">
                        <div style="position: relative;width: 100%;height: 40px;background-color: #d7d7d7">
                            <div id="timeLine" style="height: 40px;"></div>
                            <div style="position: static;">
                                <div style="width:4.1666%;display: inline-block;">00</div><!--
                            --><div style="width:4.1666%;display: inline-block;">01</div><!--
                            --><div style="width:4.1666%;display: inline-block;">02</div><!--
                            --><div style="width:4.1666%;display: inline-block;">03</div><!--
                            --><div style="width:4.1666%;display: inline-block;">04</div><!--
                            --><div style="width:4.1666%;display: inline-block;">05</div><!--
                            --><div style="width:4.1666%;display: inline-block;">06</div><!--
                            --><div style="width:4.1666%;display: inline-block;">07</div><!--
                            --><div style="width:4.1666%;display: inline-block;">08</div><!--
                            --><div style="width:4.1666%;display: inline-block;">09</div><!--
                            --><div style="width:4.1666%;display: inline-block;">10</div><!--
                            --><div style="width:4.1666%;display: inline-block;">11</div><!--
                            --><div style="width:4.1666%;display: inline-block;">12</div><!--
                            --><div style="width:4.1666%;display: inline-block;">13</div><!--
                            --><div style="width:4.1666%;display: inline-block;">14</div><!--
                            --><div style="width:4.1666%;display: inline-block;">15</div><!--
                            --><div style="width:4.1666%;display: inline-block;">16</div><!--
                            --><div style="width:4.1666%;display: inline-block;">17</div><!--
                            --><div style="width:4.1666%;display: inline-block;">18</div><!--
                            --><div style="width:4.1666%;display: inline-block;">19</div><!--
                            --><div style="width:4.1666%;display: inline-block;">20</div><!--
                            --><div style="width:4.1666%;display: inline-block;">21</div><!--
                            --><div style="width:4.1666%;display: inline-block;">22</div><!--
                            --><div style="width:4%;display: inline-block;">23</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="form-group form-group-change hidden" id="time" style="padding-top: 20px">
                        <label class="col-md-5 sie-left-name"><spring:message code="label.time"/> ：</label>

                        <div class="col-md-7" style="padding-top: 5px;">
                            <span id="startTime"></span> - <span id="endTime"></span>
                        </div>
                    </div>
                    <div id="chooseReason" class="hidden" style="display:inline-block;width: 100%">
                        <div class="form-group form-group-change" style="padding-top:20px">
                            <label class="col-md-5 sie-left-name"><spring:message code="label.offline.type"/> ：</label>

                            <div class="col-md-7">
                                <select id="type" class="form-control sie-input-border sie-input-uwh"
                                        style="padding: 2px 12px" onchange="changeOffline()">
                                    <option value="-1"><spring:message code="label.select"/></option>
                                    <option value="0">IDLE</option>
                                    <option value="1"><spring:message code="label.fault"/></option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group form-group-change" style="padding-top:20px">
                            <label class="col-md-5 sie-left-name"><spring:message code="label.reason"/> ：</label>

                            <div class="col-md-7">
                                <select id="reason" class="form-control sie-input-border sie-input-uwh"
                                        style="padding: 2px 12px">
                                    <option value="-1"><spring:message code="label.select"/></option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group form-group-change" style="padding-top: 100px;">
                            <div class="col-md-offset-5">
                                <a id="sure" class="solid-button-blue" href="javascript:;"
                                   style="margin-right: 30px"><spring:message code="label.save"/> </a>
                                <a id="cancel" class="solid-button-orange" href="javascript:;"><spring:message
                                        code="label.cancel"/> </a>
                            </div>
                        </div>
                    </div>
                    <div id="showReason" class="hidden" style="display:inline-block;width: 100%;">
                        <div class="form-group form-group-change" style="padding-top:20px">
                            <label class="col-md-5 sie-left-name"><spring:message code="label.offline.type"/>：</label>

                            <div class="col-md-7">
                                <div id="show_type" style="padding-top:5px;"></div>
                            </div>
                        </div>
                        <div class="form-group form-group-change" style="padding-top:20px">
                            <label class="col-md-5 sie-left-name"><spring:message code="label.reason"/>：</label>

                            <div class="col-md-7">
                                <div id="show_reason" style="padding-top:5px;"></div>
                            </div>
                        </div>
                        <div class="form-group form-group-change" style="padding-top:20px">
                            <label class="col-md-5 sie-left-name"><spring:message code="label.operator"/> ：</label>

                            <div class="col-md-7">
                                <div id="show_repair" style="padding-top:5px;"></div>
                            </div>
                        </div>
                        <div class="form-group form-group-change" style="padding-top: 100px;">
                            <div class="col-md-offset-5">
                                <a id="show_cancel" class="solid-button-orange" href="javascript:;"><spring:message
                                        code="label.cancel"/></a>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="otherLine" style="width: 100%">
                    <div id="other_line">

                    </div>
                </div>
            </div>
        </div>
        <%--</div>--%>
    </section>
</div>
<jsp:include page="../../include/foot.jsp"/>
<script>
    $(document).ready(function () {
        $('#hoursTimeLine').datepicker({
            language: "zh-CN",
            autoclose: true,
            format: "yyyy-mm-dd",
            endDate: dateAddSubtract(new Date(), -1),
            todayHighlight:true
        }).on('changeDate', function (ev) {
            showLine();
        });
        bindDateInputClickEvent();
        $("#hoursTimeLine").val(new Date(new Date().getTime() - 24 * 60 * 60 * 1000).toLocaleDateString().replace(new RegExp('/', 'g'), '-'));
        $("#hoursTimeLine").datepicker('update');

        $.ajax({
            url: '/partner/{tenant}/user/idle/reason/getDeviceType'.replace("{tenant}", getKeyByUrl()),
            success: function (data) {
                var types = data.data;
                if (types.length > 0) {
                    $.each(types, function (index, type) {
                        $("#deviceType").append($('<option></option>').text(type));
                    });
                } else {
                    $("#deviceType").append($('<option value="-2"></option>').text('<spring:message code="label.without"/>'));
                }
            },
            error: function () {
                swal("Error!", "", "error");
            }
        })
    });
    function changeType() {
        hideReason(true);
        $("#line").addClass("hidden");

        $("#deviceUniqueId").find("option:not(:first)").remove();
        $("#deviceModel").find("option:not(:first)").remove();

        var type = $("#deviceType").val();

        if (type == "-1") {
            return;
        }
        $.ajax({
            url: "/partner/{tenant}/user/idle/reason/getDeviceModel".replace("{tenant}", getKeyByUrl()),
            data: {
                deviceType: type
            },
            success: function (data) {
                var models = data.data;

                if (models.length > 0) {
                    $.each(models, function (index, model) {
                        $('#deviceModel').append($("<option></option>").text(model));
                    });
                } else {
                    $('#deviceModel').append($("<option value='-2'></option>").text('<spring:message code="label.without"/>'));
                }
            },
            error: function () {
                swal("Error!", "", "error");
            }
        })

    }

    function changeModel() {
        hideReason(true);
        $("#line").addClass("hidden");
        var type = $("#deviceType").val();
        var model = $('#deviceModel').val();

        if (model == "-1") {
            $("#deviceUniqueId").find("option:not(:first)").remove();
            return;
        }

        $.ajax({
            url: "/partner/{tenant}/user/idle/reason/getDeviceUniqueId".replace("{tenant}", getKeyByUrl()),
            data: {
                deviceType: type,
                deviceModel: model
            },
            success: function (data) {
                var dataArr = data.data;
                $("#deviceUniqueId").find("option:not(:first)").remove();

                if (dataArr.length > 0) {
                    $.each(dataArr, function (index, info) {
                        $('#deviceUniqueId').append($("<option></option>").text(info.device_unique_id).attr("data-id", info.device_id));
                    })
                } else {
                    $('#deviceUniqueId').append($("<option></option>").text('<spring:message code="label.without"/>'));
                }
            },
            error: function () {
                swal("Error!", "", "error");
            }
        })
    }

    function changeUniqueId() {
        showLine();
    }

    //    $('#hoursTimeLine').change(function (e) {
    //        console.log(e);
    //        showLine();
    //        loadTypeOfOneLines();
    //        loadTypeOfTowLines();
    //    });

    function showLine() {
        hideReason(true);
        $("#line").addClass("hidden");
        var uniqueId = $("#deviceUniqueId").val();
        var deviceId = $('#deviceUniqueId option:selected').data("id");
        if (uniqueId == -1 || $("#hoursTimeLine").val() == null || $("#hoursTimeLine").val() == "") {
            $("#line").addClass("hidden");
            $("#otherLine").addClass("hidden");
            return;
        } else {
            $("#line").removeClass("hidden");
            $("#otherLine").removeClass("hidden");
            otherLines();
        }
        progressBar(deviceId);
    }

    function progressBar(deviceId) {
        if ($("#hoursTimeLine").val().length == 0) {
            $("#hoursTimeLine").val(new Date().toLocaleDateString().replace(new RegExp('/', 'g'), '-'));
        }
        $.ajax({
            url: "/partner/{tenant}/api/v1/device/periodsoftime".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: {
                deviceId: deviceId,
                startTime: $('#hoursTimeLine').val()
            },
            success: function (data) {
                $("#timeLine").html('');
                $.each(data.data, function (index, map) {
                    var $a = $("<a></a>"), color, onmouseover;
                    var startTime = new Date(map.start_time).toString().substr(16, 8);
                    var endTime = new Date(map.end_time).toString().substr(16, 8);
                    if (endTime == '00:00:00') {
                        endTime = '24:00:00';
                    }
                    if (map.state == 0) {
                        color = "#d7d7d7";
                        onmouseover = "showInfo(0,this)";
                        var onclick = "writeReason('" + startTime + "','" + endTime + "')";
                        $a.attr("onclick", onclick);
                        $a.css("cursor", "pointer");
                    } else if (map.state == 1) {
                        color = "#aaaa96";
                        onmouseover = "showInfo(1,this)";
                    } else if (map.state == -1) {
                        color = "#73645a";
                        onmouseover = "showInfo(-1,this)";
                    } else {
                        color = "#d7d7d7";
                        onmouseover = "showInfo(-2,this)";
                    }
                    console.log((map.minute / (14.4 * 60)).toFixed(8) + "%");
                    $a.attr({
//                        "style": "background-color:" + color + ";width:" + (map.minute / (14.4 * 60)).toFixed(8) + "%;display:inline-block;height:40px",
                        onmouseover: onmouseover,
                        onmouseout: "removeInfo(this)",
                        "data-startTime": startTime,
                        "data-endTme": endTime
                    }).css({
                        "background-color": color,
                        "width": (map.minute / (14.4 * 60)).toFixed(8) + "%",
                        display: "inline-block",
                        height: "40px",
                        position: "relative"
                    });
                    $("#timeLine").append($a);
                });
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    function showInfo(state, _this) {
        var message;
        if (state == 0) {
            message = '<spring:message code="label.not.work"/>';
        } else if (state == 1) {
            message = '<spring:message code="label.normal.work"/>';
        } else if (state == -1) {
            message = '<spring:message code="label.plan.downtime"/>';
        } else if (state == -2) {
            message = '<spring:message code="label.unknown.state"/>';
        }

        $(_this).append($('<div class="message-box message-box-change"></div>').attr("style", "width:150px;").text(message).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
    }

    function removeInfo(_this) {
        $(_this).children().remove();
    }

    function writeReason(startTime, endTime) {
        hideReason(false);
        $('#startTime').text(startTime);
        $('#endTime').text(endTime);
        var deviceId = $('#deviceUniqueId option:selected').data("id");
        $.ajax({
            url: "/partner/{tenant}/user/idle/getOneReason".replace("{tenant}", getKeyByUrl()),
            data: {
                startTime: $('#hoursTimeLine').val() + " " + startTime,
                deviceId: deviceId
            },
            success: function (data) {
                if (data.data != null && data.data != "") {
                    var info = data.data;
                    if (info.key == 'FaultType') {
                        $("#show_type").text('<spring:message code="label.fault"/>');
                    } else if (info.key == 'IDLE') {
                        $("#show_type").text("IDLE")
                    }
                    $("#show_reason").text(info.infoReason);
                    $("#show_repair").text(info.name);
                    $("#showReason").removeClass("hidden");
                } else {
                    $("#chooseReason").removeClass("hidden");
                }
                $("#time").removeClass("hidden");
            }
        });
    }

    function changeOffline() {
        $("#reason").find("option:not(:first)").remove();
        var val = $("#type").val();
        var url;
        if (val == 0) {
            url = '/partner/{tenant}/api/v1/getIdleReasonList'.replace("{tenant}", getKeyByUrl());
        } else if (val == 1) {
            url = '/partner/{tenant}/api/v1/getFaultType'.replace("{tenant}", getKeyByUrl());
        } else if (val == -1) {
            return;
        }

        $.ajax({
            url: url,
            success: function (data) {
                if (data.result == "SUCCESS") {
                    var results = data.data;
                    $.each(results, function (index, result) {
                        var id, reason;
                        if (result.idleId == undefined) {
                            id = result.faultId;
                            reason = result.faultType;
                        } else {
                            id = result.idleId;
                            reason = result.idleName
                        }
                        $("#reason").append($("<option></option>").attr("value", id).text(reason))
                    });
//                   $("#reason").append($("<option value='other'></option>").text("其它"))
                }
            }
        })
    }

    //    function chooseOther() {
    //        var val = $("#reason").val();
    //        if (val == 'other') {
    //            $("#otherReason").removeClass("hidden");
    //        } else {
    //            $("#otherReason").addClass("hidden");
    //        }
    //    }

    $("#cancel").click(function () {
        $("#chooseReason").addClass("hidden");
        $("#time").addClass("hidden");
        $("#reason").find("option:not(:first)").remove();
        $("#type").val(-1);
    });

    $('#show_cancel').click(function () {
        $("#showReason").addClass("hidden");
        $("#time").addClass("hidden");
    });

    $("#sure").click(function () {
        var reasonId = $("#reason").val();
        var reasonType = $("#type").val();
        if (reasonId == -1 || reasonType == -1) {
            swal("Error", '<spring:message code="label.please.select.reason"/>', "error");
            return;
        }

        var startTime = $("#hoursTimeLine").val() + " " + $("#startTime").text();
        var endTime = $("#hoursTimeLine").val() + " " + $("#endTime").text();
        var deviceId = $('#deviceUniqueId option:selected').data("id");
        var repair = $('#repair').val();

        var data = {
            startTime: startTime,
            endTime: endTime,
            deviceId: deviceId,
            reasonId: reasonId
        };

        $.ajax({
            url: "/partner/{tenant}/user/idle/create".replace("{tenant}", getKeyByUrl()),
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (result) {
                $("#chooseReason").addClass("hidden");
                $("#time").addClass("hidden");
                if (result.result == "SUCCESS") {
                    swal("Success", '<spring:message code="label.add.success"/>', "success");
                } else {
                    swal("Error", result.message, "error");
                }
            }
        })
    });

    function hideReason(is) {
        $("#showReason").addClass("hidden");
        $("#time").addClass("hidden");
        $("#chooseReason").addClass("hidden");
        $("#type").val(-1);
        $("#reason").find("option:not(:first)").remove();
        $("#repair").val("");
        if (is){$("#other_line").html("");}
    }

    function loadTypeOfOthersLines(typeValues, statusTypeList) {
        var info = {}, dataSource = [];
        $.each(statusTypeList, function (index, st) {
            console.log("----------------------1--------------------");
            console.log(index);
            var names = {};
            var id = st.id;
            $.each(st.codes, function (index_, code) {
                console.log("----------------------2--------------------");
                console.log(index_);
                names[code.code] = code.name;
            });
            info[id] = names;
        });
        $.each(typeValues, function (index_, typeValue) {
            var values = typeValue.values;
            var stTypeName = typeValue.stTypeName;
            var stType = typeValue.stType;
            $.each(values, function (index, value) {
                var data = {};
                var statusType = value.statusType;
                var name = value.name;
                data['title'] = stTypeName + "(" + name + ")";
                data['statusType'] = statusType;
                data['stType'] = stType;
                dataSource.push(data);
            });
        });

        $.ajax({
            url: "/partner/{tenant}/api/v1/chartOfTypeOthers".replace("{tenant}", getKeyByUrl()),
            type: "post",
            contentType:"application/json",
            data: JSON.stringify({
                deviceId: $('#deviceUniqueId option:selected').data("id"),
                day: $('#hoursTimeLine').val(),
                dataSource: dataSource
            }),
            success: function (data) {
                $.each(data.data,function(index,d){
                    loadStaticLine(d.title,index);
                    addOtherTimeLine(d.typeTimePeriod, d.stType,info,index);
                });
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

    function loadStaticLine(title, id) {
        var staticLine = $("<div></div>").attr("style", 'position: static;');
        for (var i = 0; i < 24; i++) {
            staticLine.append($("<div></div>").attr("style", "width:4.1666%;float:left;").text(i < 9 || i == 9 ? "0" + i : i));
        }

        var show = $("<div></div>").attr("style", "min-height:0;").append(
                $("<div></div>").addClass('dashboard-chart-title').append(
                        $("<p></p>").addClass("dashboard-chart-name").text(title))).append(
                $("<div></div>").attr("style", 'padding: 20px;').append(
                        $("<div></div>").addClass('dashboard-chart-line').attr("style", "height:102px;").append(
                                $("<div></div>").addClass("static-line-border").attr({
                                    id: id,
                                    style: 'height: 40px;'
                                })).append(
                                staticLine))
        );
        $("#other_line").append(show);
    }

    function addOtherTimeLine(data, stType, info, id) {
        if (data.length == 0) {
            $("#" + id).text("无数据");
            return;
        }

        $.each(data, function (index, map) {
            var $div = $("<div></div>"), color, onmouseover, colors = ["#d7d7cd", "#aaaa96", "#73645a"];
            if (map.state == null) {
                color = "#41aaaa";
                onmouseover = "showInfos(this,\'无状态\')";
            } else {
                color = colors[map.state % 3];
                if (info[stType][map.state] == undefined) {
                    onmouseover = "showInfos(this," + map.state + ")";
                } else {
                    onmouseover = "showInfos(this,\'" + info[stType][map.state] + "\')";
                }
            }
            $div.attr("style", "background-color:" + color + ";width:" + (map.period / (864)).toFixed(8) + "%;display:inline-block;height:40px;position:relative")
                    .attr("onmouseover", onmouseover)
                    .attr("onmouseout", "removeInfo(this);");
            $("#" + id).append($div);
        });
    }

    function showInfos(_this, message) {
        $(_this).append($('<div class="message-box message-box-change"></div>').attr("style", "width:150px;").text(message).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
    }

    function otherLines() {
        $.ajax({
            url: "/partner/{tenant}/api/v1/stateTypeByDeviceType".replace("{tenant}", getKeyByUrl()),
            data: {type: $("#deviceType").val()},
            type: "get",
            success: function (data) {
                loadTypeOfOthersLines(data.data.typeValues, data.data.statusTypeList);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }
</script>